package com.ruoyi.comparison.utils;

import com.ruoyi.common.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FindAllSubUtil {

    public static List<String> getsubString(String inputString,int limit) {
        Set<String> substrings = new HashSet<>();

        for (int i = 0; i < inputString.length(); i++) {
            StringBuilder tempString = new StringBuilder();
            for (int j = i; j < inputString.length(); j++) {
                tempString.append(inputString.charAt(j));
                substrings.add(tempString.toString());
            }
        }

        List<String> collect = substrings.stream().filter(s -> s.length() >= limit).collect(Collectors.toList());

        return collect;
    }

    public static Set<String> findAllSubstrings(String input1,String input2,int limit) {
        //只保留数字、字母、中文
        String s1 = StringUtils.deleteWhitespace(input1).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "");
        String s2 = StringUtils.deleteWhitespace(input2).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "");

        Set<String> strings = new HashSet<>();
        List<String> stringList1 = getsubString(s1,limit);
        List<String> stringList2 = getsubString(s2,limit);
        for (int i = 0; i < stringList1.size(); i++) {
            for (int j = 0; j < stringList2.size(); j++) {
                if (stringList1.get(i).equals(stringList2.get(j))){
                    strings.add(stringList1.get(i));
                }
            }
        }
        List<String> collect = new ArrayList<>(strings);
        for (int i = 0; i < collect.size(); i++) {
            for (String s : collect) {
                if (collect.get(i).length() > s.length() &&
                    (!collect.get(i).equals(s)) &&
                    collect.get(i).contains(s)) {
                    strings.remove(s);
                }
            }
        }
        return strings;
    }
}
